<template>
  <div class="device-dashboard">
    <h1 class="dashboard-title">设备看板</h1>
    <!-- 加载状态增加动效 -->
    <div v-if="loading" class="loading-wrap">
      <el-skeleton loading text="loading" effect="pulse" style="width: 100px;" />
      <div class="loading-text">加载中...</div>
    </div>
    <el-row v-else :gutter="24">
      <!-- 设备情况模块 -->
      <el-col :span="16">
        <div class="device-status">
          <div class="status-group">
            <div class="status-item statistic-col">
              <div class="item-title">使用统计</div>
              <div class="item-content">
                <div class="statistic-item">
                  <span>全部设备</span>
                  <span class="number">{{ dashboardData.totalDevices }}</span>
                </div>
                <div class="statistic-item">
                  <span>在用设备</span>
                  <span class="number">{{ dashboardData.inUseDevices }}</span>
                </div>
                <div class="statistic-item">
                  <span>闲置设备</span>
                  <span class="number">{{ dashboardData.idleDevices }}</span>
                </div>
                <div class="statistic-item">
                  <span>停用设备</span>
                  <span class="number">{{ dashboardData.disabledDevices }}</span>
                </div>
              </div>
            </div>
            <div class="status-item activation-col">
              <div class="item-title">激活情况（在用设备）</div>
              <div class="item-content">
                <div class="activation-item">
                  <span>已激活设备</span>
                  <span class="number">{{ dashboardData.activatedDevices }}</span>
                </div>
                <div class="activation-item">
                  <span>未激活设备</span>
                  <span class="number orange">{{ dashboardData.unactivatedDevices }}</span>
                </div>
              </div>
            </div>
            <div class="status-item status-col">
              <div class="item-title">运行状态（已激活设备）</div>
              <div class="item-content">
                <div class="status-item">
                  <span>正常设备</span>
                  <span class="number">{{ dashboardData.normalDevices }}</span>
                </div>
                <div class="status-item">
                  <span>故障设备</span>
                  <span class="number red">{{ dashboardData.faultyDevices }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <!-- 待办事项模块 -->
      <el-col :span="8">
        <div class="todo-item">
          <h2 class="todo-title">待办事项</h2>
          <div class="todo-content">
            <div class="todo-box">
              <span>待激活</span>
              <span class="todo-number orange">2</span>
            </div>
            <div class="todo-box">
              <span>待安装</span>
              <span class="todo-number">0</span>
            </div>
            <div class="todo-box">
              <span>型号补充</span>
              <span class="todo-number">0</span>
            </div>
            <div class="todo-box">
              <span>安装地点补充</span>
              <span class="todo-number red">1</span>
            </div>
          </div>
        </div>
      </el-col>
      <!-- 设备安装分布统计模块 -->
      <el-col :span="12">
        <div class="device-map">
          <h2 class="map-title">设备安装分布统计</h2>
          <!-- 这里假设你用了 echarts 地图，可替换为实际的地图组件 -->
          <div class="map-container">
            <!-- 地图容器，可根据实际地图库调整 -->
            <div class="map-placeholder">中国地图占位</div>
            <div class="legend">
              <div v-for="(text, index) in legendTexts" :key="index" class="legend-item">
                <div :style="{background: legendColors[index]}" class="legend-dot"></div>
                <span>{{ text }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <!-- 在用设备排行模块 -->
      <el-col :span="12">
        <div class="device-rank">
          <h2 class="rank-title">在用设备排行</h2>
          <div class="rank-content">
            <!-- 这里假设是简单的条形图，可替换为实际的图表组件 -->
            <div v-for="(item, index) in rankData" :key="index" class="rank-item">
              <span class="rank-name">{{ item.name }}</span>
              <div class="rank-bar">
                <div :style="{width: item.percent}" class="bar-fill"></div>
              </div>
              <span class="rank-number">{{ item.value }}</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElSkeleton } from 'element-plus';
import request from '@/utils/request';

const API_URL = import.meta.env.VITE_DEVICE_DASHBOARD_API || '/Dev/deviceDashboard';

const dashboardData = ref({
  totalDevices: 276,
  inUseDevices: 260,
  idleDevices: 10,
  disabledDevices: 6,
  activatedDevices: 212,
  unactivatedDevices: 48,
  normalDevices: 208,
  faultyDevices: 4
});
const loading = ref(true);

// 模拟地图图例数据
const legendTexts = [
  '100台以上',
  '80台以上',
  '60台以上',
  '40台以上',
  '20台以上',
  '10台以上',
  '1台以上'
];
const legendColors = [
  '#002F6C',
  '#1F4E8C',
  '#3C6EBD',
  '#5A8FD1',
  '#78B0E3',
  '#96D2F5',
  '#B4F4FF'
];

// 模拟在用设备排行数据
const rankData = [
  { name: '光刻机', value: 94, percent: '94%' },
  { name: '刻蚀机', value: 79, percent: '79%' },
  { name: '薄膜沉积设备', value: 60, percent: '60%' },
  { name: '离子注入机', value: 45, percent: '45%' },
  { name: '机械抛光', value: 40, percent: '40%' },
  { name: '清洗机', value: 21, percent: '21%' },
  { name: '氧化炉', value: 18, percent: '18%' },
  { name: '晶圆切割机', value: 15, percent: '15%' },
  { name: '晶元建薄机', value: 11, percent: '11%' },
  { name: '测试机', value: 8, percent: '8%' }
];

const formatKey = (key) => {
  const keyMap = {
    totalDevices: '全部设备',
    inUseDevices: '在用设备',
    idleDevices: '闲置设备',
    disabledDevices: '停用设备',
    activatedDevices: '已激活设备',
    unactivatedDevices: '未激活设备',
    normalDevices: '正常设备',
    faultyDevices: '故障设备'
  };
  return keyMap[key] || key;
};

const validateResponseData = (data) => {
  const expectedKeys = Object.keys(dashboardData.value);
  return expectedKeys.every(key => key in data);
};

const fetchDashboardData = async () => {
  try {
    loading.value = true;
    const response = await request.get(API_URL);
    console.log('API响应:', response);

    let responseData = response.data;
    // 兼容后端封装格式
    if (responseData && responseData.data) {
      responseData = responseData.data;
    }

    if (validateResponseData(responseData)) {
      dashboardData.value = responseData;
    } else {
      throw new Error('返回数据格式不正确');
    }
  } catch (error) {
    if (error.response && error.response.status === 403) {
      ElMessage.error('权限不足，无法获取设备数据');
    } else {
      ElMessage.error('获取设备数据失败，请稍后重试');
    }
    console.error('获取设备数据错误:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchDashboardData();
});
</script>

<style scoped>
.device-dashboard {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.dashboard-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}

/* 加载状态优化 */
.loading-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.loading-text {
  margin-top: 12px;
  color: #999;
}

/* 设备情况模块 */
.device-status {
  margin-bottom: 24px;
}

.status-group {
  display: flex;
  justify-content: space-between;
}

.status-item {
  flex: 1;
  margin-right: 12px;
  border-radius: 8px;
  padding: 16px;
}

.status-item:last-child {
  margin-right: 0;
}

.statistic-col {
  background: #e9f5ff;
}

.activation-col {
  background: #fff8e6;
}

.status-col {
  background: #ffe6e6;
}

.item-title {
  font-size: 14px;
  color: #666;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
  margin-bottom: 12px;
}

.item-content {
  display: flex;
  justify-content: space-around;
}

.statistic-item,
.activation-item,
.status-item {
  text-align: center;
}

.number {
  display: block;
  font-size: 20px;
  font-weight: 500;
  color: #333;
  margin-top: 8px;
}

.orange {
  color: #f7931a;
}

.red {
  color: #f56c6c;
}

/* 待办事项模块 */
.todo-item {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
}

.todo-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.todo-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.todo-box {
  width: 48%;
  background: #fff;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.todo-number {
  float: right;
  font-weight: 500;
}

/* 设备安装分布统计模块 */
.device-map {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
}

.map-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.map-container {
  position: relative;
  padding-bottom: 60%;
  /* 控制地图高度比例 */
}

.map-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 80%;
  background: #eee;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
}

.legend {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  padding: 8px 0;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 0 8px;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 4px;
}

/* 在用设备排行模块 */
.device-rank {
  background: #f9f9f9;
  border-radius: 8px;
  padding: 16px;
}

.rank-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.rank-content {
  padding: 0 12px;
}

.rank-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.rank-name {
  flex: 1;
  margin-right: 12px;
  color: #666;
}

.rank-bar {
  width: 60%;
  height: 12px;
  background: #eee;
  border-radius: 6px;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  background: #409eff;
}

.rank-number {
  width: 30px;
  text-align: right;
  color: #333;
  font-weight: 500;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .status-group {
    flex-direction: column;
  }

  .status-item {
    margin-right: 0;
    margin-bottom: 12px;
  }

  .todo-box {
    width: 100%;
  }
}

@media (max-width: 992px) {
  .el-col {
    span: 24 !important;
    margin-bottom: 20px;
  }
}
</style>